package com.minishift.android.utils;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Process;

/**
 * 
 * this class is activities mananger.
 * @author Sirier
 *
 */
public class XActivitiyManager {

	private static Stack<Activity> activityStack;
	private static XActivitiyManager instance;
	
	private XActivitiyManager(){}
	
	/**
	 * this method will get only object of XActivityManager.
	 * @return InitAction: only object of XActivityManager.
	 */
	public static XActivitiyManager getXActivityManager(){
		if(null == instance){
			instance = new XActivitiyManager();
		}
		return instance;
	}
	
	/**
     * this method will let current activity add to application's stack.
     */ 
    public void addActivity(Activity activity){ 
        if(activityStack==null){ 
            activityStack=new Stack<Activity>(); 
        } 
        activityStack.add(activity); 
    } 
    
    /**
     * this method will get current activity that is the lasttest in stack.
     */ 
    public Activity currentActivity(){ 
        Activity activity=activityStack.lastElement(); 
        return activity; 
    } 
    
    /**
     * this method will finish current activity that is the lasttest in stack.
     */ 
    public void finishActivity(){ 
        Activity activity=activityStack.lastElement(); 
        if(activity!=null){ 
            activity.finish(); 
            activity=null; 
        } 
    } 
    
    /**
     * this method will finish selected activity.
     */ 
    public void finishActivity(Activity activity){ 
        if(activity!=null){ 
            activityStack.remove(activity); 
            activity.finish(); 
            activity=null; 
        } 
    } 
    
    /**
     * this method will finish selected and name of param activity. 
     */ 
    public void finishActivity(Class<?> cls){ 
        for (Activity activity : activityStack) { 
            if(activity.getClass().equals(cls) ){ 
                finishActivity(activity); 
            } 
        } 
    } 
    
    /**
     * this method will finish all activity.
     */ 
    public void finishAllActivity(){ 
        for (int i = 0, size = activityStack.size(); i < size; i++){ 
            if (null != activityStack.get(i)){ 
                activityStack.get(i).finish(); 
            } 
        } 
        activityStack.clear(); 
    } 
    
    /**
     * this method will exit the application.
     */ 
    @SuppressWarnings("deprecation")
	public void ApplicationExit(Context context) { 
        try { 
            finishAllActivity(); 
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            manager.restartPackage(context.getPackageName());
            Process.killProcess(Process.myPid());
            System.exit(0);
        } catch (Exception e) { } 
    } 
} 
